#!/usr/bin/env python3
"""
Example usage of the enhanced OCR API endpoint
"""

import requests
from pathlib import Path

# API配置
API_BASE_URL = "http://localhost:8001"
API_ENDPOINT = "/api/ocr/recognize"

def upload_and_recognize_image(image_path, language="ch", confidence_threshold=0.5):
    """
    上传图片并进行OCR识别
    
    Args:
        image_path: 图片文件路径
        language: 识别语言 (ch=中英文, en=英文, fr=法语等)
        confidence_threshold: 置信度阈值 (0.0-1.0)
    
    Returns:
        dict: OCR识别结果
    """
    
    # 检查文件是否存在
    if not Path(image_path).exists():
        raise FileNotFoundError(f"图片文件不存在: {image_path}")
    
    # 准备请求参数
    params = {
        "language": language,
        "confidence_threshold": confidence_threshold,
        "use_angle_cls": True
    }
    
    # 上传文件并处理
    try:
        with open(image_path, 'rb') as f:
            files = {'file': (Path(image_path).name, f, 'image/png')}
            
            print(f"正在上传并识别图片: {image_path}")
            print(f"参数: language={language}, confidence_threshold={confidence_threshold}")
            
            response = requests.post(
                f"{API_BASE_URL}{API_ENDPOINT}",
                files=files,
                params=params
            )
        
        # 处理响应
        if response.status_code == 200:
            result = response.json()
            return result
        else:
            raise Exception(f"API请求失败: {response.status_code} - {response.text}")
            
    except Exception as e:
        raise Exception(f"OCR处理失败: {str(e)}")

def print_ocr_results(result):
    """打印OCR识别结果"""
    
    if not result['success']:
        print(f"❌ 识别失败: {result['message']}")
        return
    
    data = result['data']
    
    print("\\n" + "="*60)
    print("📋 OCR识别结果")
    print("="*60)
    print(f"✅ 状态: {result['message']}")
    print(f"⏱️  处理时间: {data['processing_time']:.2f}秒")
    print(f"🌐 使用语言: {data['language_used']}")
    print(f"📊 平均置信度: {data['average_confidence']:.3f}")
    print(f"📝 总字符数: {data['total_characters']}")
    print(f"🔍 识别区域数: {len(data['results'])}")
    
    print(f"\\n📄 完整文本:\\n{data['total_text']}")
    
    if data['results']:
        print(f"\\n📍 详细识别结果:")
        for i, item in enumerate(data['results'], 1):
            print(f"  {i}. 文本: '{item['text']}'")
            print(f"     置信度: {item['confidence']:.3f}")
            print(f"     坐标: {item['bbox']}")
            print()

def main():
    """主函数示例"""
    
    print("🚀 OCR API 使用示例")
    print("="*50)
    
    # 示例1: 基本使用
    try:
        # 使用测试图片
        image_path = "enhanced_test_image.png"
        
        # 如果测试图片不存在，创建一个
        if not Path(image_path).exists():
            print("📷 创建测试图片...")
            from PIL import Image, ImageDraw, ImageFont
            
            img = Image.new('RGB', (600, 300), color=(255, 255, 255))
            draw = ImageDraw.Draw(img)
            
            try:
                font = ImageFont.truetype("arial.ttf", 36)
            except:
                font = ImageFont.load_default()
            
            draw.text((50, 50), "Hello OCR API", fill=(0, 0, 0), font=font)
            draw.text((50, 120), "图像文字识别", fill=(0, 0, 0), font=font)
            draw.text((50, 190), "Phone: +86-123-4567", fill=(0, 0, 0), font=font)
            
            img.save(image_path)
            print(f"✅ 测试图片已创建: {image_path}")
        
        # 进行OCR识别
        result = upload_and_recognize_image(
            image_path=image_path,
            language="ch",  # 中英文识别
            confidence_threshold=0.3  # 较低的置信度阈值
        )
        
        # 打印结果
        print_ocr_results(result)
        
    except Exception as e:
        print(f"❌ 示例执行失败: {e}")
    
    print("\\n" + "="*50)
    print("📚 API使用说明:")
    print("1. POST /api/ocr/recognize - 上传图片进行OCR识别")
    print("2. 支持参数:")
    print("   - language: 识别语言 (ch, en, fr, german, korean等)")
    print("   - confidence_threshold: 置信度阈值 (0.0-1.0)")
    print("   - use_angle_cls: 是否使用角度分类 (true/false)")
    print("3. 支持格式: JPG, PNG, BMP, TIFF, WebP")
    print("4. 文件大小限制: 10MB")
    print("\\n💡 提示: 使用更高的置信度阈值可以过滤掉低质量的识别结果")

if __name__ == "__main__":
    main()